Custom Exception তৈরি এবং হ্যান্ডল করা

Java Technologies - জ্যাকসন (Jackson) - Jackson এর Error Handling এবং Exception Management
170

Spring Framework এবং Jackson একসঙ্গে JSON ডেটা হ্যান্ডল করতে এবং API তে একক ফরম্যাটে এক্সসেপশন ম্যানেজ করতে ব্যবহার করা হয়। Spring Framework এ @RestControllerAdvice এবং @ExceptionHandler ব্যবহার করে কাস্টম এক্সসেপশন তৈরি এবং হ্যান্ডল করা যায়।


Custom Exception তৈরি

১. একটি Custom Exception ক্লাস তৈরি করুন

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}

Custom Exception Handling

২. @RestControllerAdvice ব্যবহার করে Exception Handling

Spring Framework এ @RestControllerAdvice গ্লোবালভাবে এক্সসেপশন হ্যান্ডল করার জন্য ব্যবহৃত হয়।

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<Map<String, String>> handleUserNotFoundException(UserNotFoundException ex) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", "User Not Found");
        errorResponse.put("message", ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, String>> handleGenericException(Exception ex) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", "Internal Server Error");
        errorResponse.put("message", ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Controller-এ Exception Trigger করা

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public String getUser(@PathVariable String id) {
        if ("123".equals(id)) {
            return "User found!";
        } else {
            throw new UserNotFoundException("User with ID " + id + " not found.");
        }
    }
}

API Behavior

Valid Request:

GET Request:

GET /users/123

Response:

User found!

Invalid Request:

GET Request:

GET /users/456

Response:

{
  "error": "User Not Found",
  "message": "User with ID 456 not found."
}

Custom Exception Serialization

Jackson ব্যবহার করে কাস্টম এক্সসেপশনকে JSON ফরম্যাটে কাস্টমাইজ করতে @JsonSerialize ব্যবহার করা যায়।

Custom Exception Serialization

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonSerialize(using = CustomExceptionSerializer.class)
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}

Custom Serializer তৈরি

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;

public class CustomExceptionSerializer extends StdSerializer<UserNotFoundException> {

    public CustomExceptionSerializer() {
        super(UserNotFoundException.class);
    }

    @Override
    public void serialize(UserNotFoundException exception, JsonGenerator gen, SerializerProvider provider)
            throws IOException {
        gen.writeStartObject();
        gen.writeStringField("type", "UserNotFoundException");
        gen.writeStringField("message", exception.getMessage());
        gen.writeEndObject();
    }
}

Response with Custom Serialization

GET Request (Invalid):

GET /users/456

Response:

{
  "type": "UserNotFoundException",
  "message": "User with ID 456 not found."
}

Custom Exception with More Details

Exception Class:

public class ApiError {
    private String error;
    private String message;
    private int statusCode;

    // Constructor, Getters and Setters
    public ApiError(String error, String message, int statusCode) {
        this.error = error;
        this.message = message;
        this.statusCode = statusCode;
    }
}

Enhanced Exception Handler:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<ApiError> handleUserNotFoundException(UserNotFoundException ex) {
        ApiError error = new ApiError("User Not Found", ex.getMessage(), HttpStatus.NOT_FOUND.value());
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiError> handleGenericException(Exception ex) {
        ApiError error = new ApiError("Internal Server Error", ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value());
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

API Response Example

GET Request (Invalid):

GET /users/456

Response:

{
  "error": "User Not Found",
  "message": "User with ID 456 not found.",
  "statusCode": 404
}

  1. Spring Framework এবং Jackson একসঙ্গে ব্যবহার করে Exception Management সহজে কাস্টমাইজ করা যায়।
  2. @RestControllerAdvice এবং @ExceptionHandler Exception হ্যান্ডলিংয়ের জন্য একটি গ্লোবাল মেকানিজম প্রদান করে।
  3. Custom Serializer ব্যবহার করে Exception এর JSON ফরম্যাট সম্পূর্ণ নিয়ন্ত্রণ করা যায়।
  4. REST API ডেভেলপমেন্টে ব্যবহারকারীর জন্য একটি হিউম্যান-রিডেবল এবং কনসিস্টেন্ট এক্সসেপশন ফরম্যাট নিশ্চিত করা যায়।
Content added By
Promotion
NEW SATT AI এখন আপনাকে সাহায্য করতে পারে।

Are you sure to start over?

Loading...